package com.words.config.auth;

import cn.hutool.json.JSONUtil;
import com.words.result.Result;
import com.words.untils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//登陆成功处理器
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtTokenUtils jwtTokenUtils;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream =response.getOutputStream();
        //生成jwt，并放置在表头
        Map<String,String> map= new HashMap<>();
        map.put("username",authentication.getName());
        String token = jwtTokenUtils.getToken(map);

        response.setHeader("token",token);

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        System.out.println(principal);
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String role = Arrays.stream(authorities.toArray()).findFirst().toString();

        Result result = Result.init(200,"登录成功",role);

        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
